define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'bootstrap-table-editable'], function ($, undefined, Backend, Table, Form, undefined) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'box/box/index',
                    add_url: 'box/box/add',
                    edit_url: 'box/box/edit',
                    del_url: 'box/box/del',
                    multi_url: 'box/box/multi',
                    table: 'box',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'box_id',
                sortName: 'box_id',
                searchFormVisible: false,
                searchFormTemplate: 'customformtpl',
                queryParams: function (params) {
//                        var options = table.bootstrapTable('getOptions');
                    //这里可以追加搜索条件
//                        var filter = JSON.parse(params.filter);
//                        var op = JSON.parse(params.op);
//                        filter.referee_id=Fast.api.query('ref');
//                        params.filter = JSON.stringify(filter);
//                        params.op = JSON.stringify(op);
//                        return params;
                    var options = table.bootstrapTable('getOptions');
                    var filter = JSON.parse(params.filter);
                    filter.status = 1;
                    params.filter = JSON.stringify(filter);

                    return params;
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'box_no', title: __('Box_no')},
                        {field: 'user_id', title: __('User_id')},
                        {field: 'area', title: __('Area'), formatter: Controller.api.formatter.city_info},
                        {field: 'room', title: __('Room'), formatter: Controller.api.formatter.house_info},
                        {field: 'contacts', title: __('Contacts')},
                        {field: 'sex', title: __('性别')},
                        {field: 'telephone', title: __('Telephone')},
                        {field: 'admin_name', title: __('Admin_name')},
                        {field: 'remark', title: __('Remark')},
                        {field: 'camp_on_admin', title: __('Camp_on_admin')},
                        {field: 'camp_on_time', title: __('Camp_on_time'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'createtime', title: __('Createtime'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'place_time_start', title: __('Place_time_start'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        //自定义栏位,custom是不存在的字段
                        {
                            field: 'custom',
                            title: __('操作'),
                            operate: false,
                            width: '80px',
                            formatter: Controller.api.formatter.custom
                        }
                    ]
                ]
            });

            $('#table').bootstrapTable('hideColumn', 'camp_on_admin');
            $('#table').bootstrapTable('hideColumn', 'camp_on_time');
            $('#daochu').hide();
            $('#yuzan').hide();
            $('#quxiaoyuzan').hide();
            $('#sanchu').hide();

            //绑定TAB事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {


                // var options = table.bootstrapTable(tableOptions);
                var typeStr = $(this).attr("href").replace('#', '');
                var options = table.bootstrapTable('getOptions');
                var queryParams = options.queryParams;
                options.queryParams = function (params) {
                    //这一行必须要存在,否则在点击下一页时会丢失搜索栏数据
                    params = queryParams(params);
                    var filter = params.filter ? JSON.parse(params.filter) : {};
                    var op = params.op ? JSON.parse(params.op) : {};
                    if (typeStr == 'one') {
                        $('#table').bootstrapTable('showColumn', 'user_id');
                        $('#table').bootstrapTable('showColumn', 'area');
                        $('#table').bootstrapTable('showColumn', 'room');
                        $('#table').bootstrapTable('showColumn', 'contacts');
                        $('#table').bootstrapTable('showColumn', 'sex');
                        $('#table').bootstrapTable('showColumn', 'telephone');
                        $('#table').bootstrapTable('showColumn', 'remark');
                        $('#table').bootstrapTable('showColumn', 'place_time_start');
                        $('#table').bootstrapTable('hideColumn', 'camp_on_admin');
                        $('#table').bootstrapTable('hideColumn', 'camp_on_time');
                        $('#daochu').hide();
                        $('#yuzan').hide();
                        $('#quxiaoyuzan').hide();
                        $('#piliangfenpei').hide();
                        $('#sanchu').hide();

                        filter.status = 1;
                    }

                    if (typeStr == 'two') {
                        $('#table').bootstrapTable('hideColumn', 'user_id');
                        $('#table').bootstrapTable('hideColumn', 'area');
                        $('#table').bootstrapTable('hideColumn', 'room');
                        $('#table').bootstrapTable('hideColumn', 'contacts');
                        $('#table').bootstrapTable('hideColumn', 'sex');
                        $('#table').bootstrapTable('hideColumn', 'telephone');
                        $('#table').bootstrapTable('hideColumn', 'remark');
                        $('#table').bootstrapTable('hideColumn', 'place_time_start');
                        $('#table').bootstrapTable('showColumn', 'camp_on_admin');
                        $('#table').bootstrapTable('showColumn', 'camp_on_time');
                        $('#daochu').show();
                        $('#quxiaoyuzan').show();
                        $('#piliangfenpei').show();
                        $('#yuzan').hide();
                        $('#sanchu').hide();
                        filter.status = 10;

                    }

                    if (typeStr == 'three') {
                        $('#table').bootstrapTable('hideColumn', 'user_id');
                        $('#table').bootstrapTable('hideColumn', 'area');
                        $('#table').bootstrapTable('hideColumn', 'room');
                        $('#table').bootstrapTable('hideColumn', 'contacts');
                        $('#table').bootstrapTable('hideColumn', 'sex');
                        $('#table').bootstrapTable('hideColumn', 'telephone');
                        $('#table').bootstrapTable('hideColumn', 'remark');
                        $('#table').bootstrapTable('hideColumn', 'place_time_start');
                        $('#table').bootstrapTable('hideColumn', 'camp_on_admin');
                        $('#table').bootstrapTable('hideColumn', 'camp_on_time');
                        $('#daochu').show();
                        $('#yuzan').show();
                        $('#quxiaoyuzan').hide();
                        $('#piliangfenpei').hide();
                        $('#sanchu').show();
                        filter.status = 0;

                    }
                    params.filter = JSON.stringify(filter);
                    params.op = JSON.stringify(op);

                    return params;
                };
                table.bootstrapTable('refresh', {});
                return false;

            });

            $(table).on("click", "[data-id].btn-hshz", function (e) {
                e.preventDefault();
                var id = $(this).data("id");
                var that = this;
                var url = $(that).data("url");
                Layer.prompt({title: __('回收原因'), formType: 0}, function (value, index) {
                    Backend.api.ajax({
                        url: url + "?user_box_id=" + id + "&recovery_reason=" + value,
                        data: $(that).closest("form").serialize()
                    }, function () {
                        table.bootstrapTable('refresh', {});
                    });

                    Layer.close(index);
                });
            });

            $(table).on("click", "[data-id].btn-qxyz", function (e) {
                e.preventDefault();
                var id = $(this).data("id");

                var that = this;
                Layer.confirm(
                        __('确定取消预占该盒子吗？'),
                        {icon: 3, title: __('确定取消预占该盒子吗？'), shadeClose: true},
                        function (index) {
                            $.post('box/box/quxiaoyuzan', {ids: id}, function (res) {
                                table.bootstrapTable('refresh', {});
                            });
                            Layer.close(index);
                        }
                );
            });

            $(table).on("click", "[data-id].btn-yzhz", function (e) {
                e.preventDefault();
                var id = $(this).data("id");

                var that = this;
                Layer.confirm(
                        __('确定预占盒子吗？'),
                        {icon: 3, title: __('确定预占盒子吗？'), shadeClose: true},
                        function (index) {
                            $.post('box/box/yuzan', {ids: id}, function (res) {
                                table.bootstrapTable('refresh', {});
                            });
                            Layer.close(index);
                        }
                );
            });

            $(table).on("click", "[data-id].btn-schz", function (e) {
                e.preventDefault();
                var id = $(this).data("id");

                var that = this;
                Layer.confirm(
                        __('确定删除盒子吗？'),
                        {icon: 3, title: __('确定删除盒子吗？'), shadeClose: true},
                        function (index) {
                            $.post('box/box/delbox', {ids: id}, function (res) {
                                table.bootstrapTable('refresh', {});
                            });
                            Layer.close(index);
                        }
                );
            });

            $(document).on("click", ".view-screenshots", function () {
                var data = [];

                var src = $(this).data("src");

                data.push({
                    "src": src
                });

                var json = {
                    "title": '消费二维码',
                    "data": data
                };
                top.Layer.photos(top.JSON.parse(JSON.stringify({photos: json})));
            });

            // 导出消费二维码
            $(document).on("click", ".btn-daochu", function () {
                var ids = Table.api.selectedids(table);
                window.location.href = 'box/exportqrcode/ids/' + ids.join(",");

            });


            // 批量预占
            $(document).on("click", ".btn-yuzan", function () {
                var ids = Table.api.selectedids(table);
                Layer.confirm(
                        __('确定预占这些盒子吗？'),
                        {icon: 3, title: __('确定预占这些盒子吗？'), shadeClose: true},
                        function (index) {
                            $.post('box/box/yuzan', {ids: ids.join(",")}, function (res) {
                                table.bootstrapTable('refresh', {});
                            });
                            Layer.close(index);
                        }
                );

            });

            // 批量取消预占
            $(document).on("click", ".btn-quxiaoyuzan", function () {
                var ids = Table.api.selectedids(table);
                Layer.confirm(
                        __('确定取消预占这些盒子吗？'),
                        {icon: 3, title: __('确定取消预占这些盒子吗？'), shadeClose: true},
                        function (index) {
                            $.post('box/box/quxiaoyuzan', {ids: ids.join(",")}, function (res) {
                                table.bootstrapTable('refresh', {});
                            });
                            Layer.close(index);
                        }
                );

            });

            // 批量删除
            $(document).on("click", ".btn-sanchu", function () {
                var ids = Table.api.selectedids(table);
                Layer.confirm(
                        __('确定删除这些盒子吗？'),
                        {icon: 3, title: __('确定删除这些盒子吗？'), shadeClose: true},
                        function (index) {
                            $.post('box/box/delbox', {ids: ids.join(",")}, function (res) {
                                table.bootstrapTable('refresh', {});
                            });
                            Layer.close(index);
                        }
                );

            });

            // 批量预占
            $(document).on("click", ".btn-piliangfenpei", function () {
                var ids = Table.api.selectedids(table);
                $.post('box/box/isyuzan', {ids: ids.join(",")}, function (res) {
                    if (res.code == 1) {
                        Backend.api.open('box/box/allot/ids/' + ids.join(","), __('批量分配'), {area: ["90%", "90%"]}, {
                            callback: function (value) {
                                table.bootstrapTable('refresh', {});
                            },
                        });
                    } else {
                        Layer.alert(res.msg);
                        return;
                    }
                });
            });

            //分配用户
            $(document).on("click", ".btn-fpyh", function () {
                var ids = $(this).data("id");
                Backend.api.open('box/box/allot/ids/' + ids, __('分配用户'), {area: ["90%", "90%"]}, {
                    callback: function (value) {
                        table.bootstrapTable('refresh', {});
                    },
                });

            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        allot: function () {
            var table2 = $("#table");
            var ids = table2.attr('ids');
            var box_id = table2.attr('box-ids');
            var is_have_goods = table2.attr('is-have-goods');
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'box/box/goodslist?ids=' + box_id,
                    add_url: 'box/userbox/add',
                    edit_url: 'box/userbox/allot',
                    del_url: 'box/userbox/del',
                    multi_url: 'box/userbox/multi',
                    table: 'user_box',
                }
            });



            // 初始化表格
            table2.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'goods_id',
                sortName: 'goods_id',
                toolbar: '#toolbar1',
                showRefresh: true,
                commonSearch: false,
                columns: [
                    [
                        {field: 'goods_id', title: __('Goods_id')},
                        {field: 'goods_title', title: __('Goods_title'), formatter: Controller.api.formatter.goods_info, operate: false, align: 'left'},
                        {field: 'brand_title', title: __('Brand_title'), operate: false},
                        {field: 'cate_title', title: __('Cate_title'), operate: false},
                        {field: 'purchase_price', title: __('Purchase_price'), operate: false},
                        {field: 'goods_price', title: __('Goods_price'), operate: false},
                        {field: 'selling_price', title: __('Selling_price'), operate: false},
                        {field: 'goods_weight', title: __('Goods_weight'), operate: false},
                        {
                            field: 'stock_num',
                            title: __('Stock_num'),
                            editable: {
                                type: 'text'
                            }
                        },
                        {field: 'createtime', title: __('Goods_createtime'), operate: false},
                        //自定义栏位,custom是不存在的字段
                        {
                            field: 'goods_custom',
                            title: __('操作'),
                            operate: false,
                            width: '80px',
                            formatter: Controller.api.formatter.goods_custom
                        },
                    ]
                ],
                onEditableSave: function (field, row, oldValue, $el) {
                    $.ajax({
                        type: "post",
                        url: "box/userbox/editstock?ids=" + ids,
                        data: row,
                        dataType: 'JSON',
                        success: function (data, status) {
                            if (status == "success") {
                                Toastr.success('操作成功');
                            }
                        },
                        error: function () {
                            Toastr.success('编辑失败');
                        },
                    });
                }
            });

            if (is_have_goods == 1) {
                $('.btn-save-user').hide();
                $('#c-province').attr("disabled", "disabled");
                $('#c-city').attr("disabled", "disabled");
                $('#c-area').attr("disabled", "disabled");
                $('#c-quarters').attr("disabled", "disabled");
            }

            $(document).on('change', ".have-goods", function () {

                if (is_have_goods == 1) {
                    $(this).attr("disabled", "disabled");
                }
            });

            $(document).on("click", "[data-id].btn-refresh", function (e) {

                table2.bootstrapTable('refresh', {});
            });

            $(document).on("click", ".btn-addgoods", function (e) {
                ids = table2.attr('ids');
                Backend.api.open('box/userbox/addgoods?ids=' + ids, __('添加盒子商品'), {
                    callback: function (value) {
                        table2.bootstrapTable('refresh', {});
                    }
                });
            });

            $(table2).on("click", "[data-id].btn-delgoods", function (e) {
                ids = table2.attr('ids');
                e.preventDefault();
                var id = $(this).data("id");

                var that = this;
                Layer.confirm(
                        __('确定删除盒子商品吗？'),
                        {icon: 3, title: __('确定删除盒子商品吗？'), shadeClose: true},
                        function (index) {
                            $.post('box/userbox/delgoods', {id: id, ids: ids}, function (res) {
                                table2.bootstrapTable('refresh', {});
                            });
                            Layer.close(index);
                        }
                );
            });


            //分配用户
            $(document).on("click", ".btn-save-user", function () {
//                var row = new Array();

                var ids = $('#ids').val();
                var user_id = $('#c-user_id').val();


                var contacts = $('#c-contacts').val();
                var sex = $('#c-sex').val();
                var telephone = $('#c-telephone').val();
                var remark = $('#c-remark').val();

                var province = $('#c-province').val();
                var city = $('#c-city').val();
                var area = $('#c-area').val();
                var quarters = $('#c-quarters').val();
                var unit_id = $('#c-unit_id').val();
                var room_id = $('#c-room_id').val();


                var row = {user_id: user_id, contacts: contacts,sex:sex, telephone: telephone, remark: remark};

                $.post('box/box/allot', {ids: ids, row: row, province: province, city: city, area: area, quarters: quarters, unit_id: unit_id, room_id: room_id}, function (res) {
                    if (res.data.is_add_goods == 1) {
                        ids = res.data.user_box_id;
                        table2.attr('ids', res.data.user_box_id);
                        $('.btn-addgoods').show();
                        $('.btn-save-user').hide();
                    } else {
                        Layer.alert(res.msg);
                        return;
                    }
                });

            });


            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {//渲染的方法
                city_info: function (value, row, index) {
                    var html = row.province_name + '-' + row.city_name + '-' + row.area_name;
                    return html;
                },
                house_info: function (value, row, index) {

                    var html = row.quarters_name + '-' + row.unit_name + '-' + row.room_name;
                    return html;
                },
                goods_custom: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    var html = '';
                    html += '<a class="text-danger btn-delgoods"  style="cursor:pointer" data-url="box/userbox/delgoods" data-id="' + row.goods_id + '"><b>删除</b></a>';

                    return html;
                },
                custom: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    var html = '';
                    if (row.status == 10) {
                        html += '<a class="text-warning btn-fpyh"  style="cursor:pointer"  data-id="' + row.box_id + '"><b>分配用户</b></a>';
                        html += '|<a class="btn-xfewm view-screenshots" data-src="https://www.mohebianli.com/uploads/box/' + row.box_no + '.png"  style="cursor:pointer"  data-id="' + row.box_id + '"><b>消费二维码</b></a>';
                        html += '|<a class="text-danger btn-qxyz"  style="cursor:pointer"  data-id="' + row.box_id + '"><b>取消预占</b></a>';
                    }

                    if (row.status == 0) {
                        html += '<a class="text-warning btn-yzhz "  style="cursor:pointer"  data-id="' + row.box_id + '"><b>预占盒子</b></a>';
                        html += '|<a class="btn-xfewm view-screenshots"  data-src="https://www.mohebianli.com/uploads/box/' + row.box_no + '.png" style="cursor:pointer"  data-id="' + row.box_id + '"><b>消费二维码</b></a>';
                        html += '|<a class="text-danger btn-schz"  style="cursor:pointer"  data-id="' + row.box_id + '"><b>删除盒子</b></a>';
                    }

                    if (row.status == 1) {
                        html += '<a class="btn-xfewm view-screenshots"  data-src="https://www.mohebianli.com/uploads/box/' + row.box_no + '.png"  style="cursor:pointer"  data-id="' + row.box_id + '"><b>消费二维码</b></a>';
                        html += '|<a class="text-danger btn-hshz"  style="cursor:pointer" data-url="box/box/huishou" data-id="' + row.user_box_id + '"><b>回收盒子</b></a>';
                    }

                    html += '|<a href="box/box/laying?ids=' + row.box_id + '" class="text-success btn-bfjl btn-dialog" title="盒子布放记录" style="cursor:pointer"  data-id="' + row.box_id + '"><b>布放记录</b></a>';
                    return html;
                }
            },
        }
    };
    return Controller;
});